package com.tledu.production.controller.common;

import com.tledu.production.constant.SessionConstant;
import com.tledu.production.core.result.AjaxResult;
import com.tledu.production.model.system.SysRes;
import com.tledu.production.model.system.SysUser;
import com.tledu.production.service.system.ISysResService;
import com.tledu.production.service.system.ISysRoleResService;
import com.tledu.production.service.system.ISysUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Antg
 * @date 2021/8/15  21:49
 */
@Controller
@AllArgsConstructor
public class CommonLoginController {
    private final ISysUserService sysUserService;
    private final ISysRoleResService sysRoleResService;
    private final ISysResService sysResService;

    //登录
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(String username, String password, HttpSession session) {
        //认证
        SysUser user = sysUserService.login(username, password);
        session.setAttribute(SessionConstant.LOGINUSER, user);

        //判断用户是否被锁定
        if (user.getLocked() == '1') {
            return new AjaxResult("用户被锁定,请联系管理员解除", 500);
        }

        //授权
        //查询用户角色
        String roleId = user.getRoleId();
        //查询角色对应的资源id列表
        Integer[] resIds = sysRoleResService.findRoleRes(roleId);

        //判断该用户是否用权限
        if (resIds == null) {
            return new AjaxResult("用户还未分配任何权限,请联系管理员", 500);
        }


        //查询这些资源的连接
        List<SysRes> resList = sysResService.findByIds(resIds);
        List<String> auth = new ArrayList<>();
        for (SysRes sysRes : resList) {
            auth.add(sysRes.getResLink());
        }
        //加入到session中
        session.setAttribute(SessionConstant.AUTH, auth);
        return new AjaxResult("登录成功");
    }

    //跳转登录页面
    @GetMapping("/login")
    public String login() {
        return "login";
    }


}
